<template>
  <!-- 子项目新增 -->
  <div class="app-container-add">
    <!-- 功能按钮 -->
    <el-row :gutter="10" class="button-wrap" :style="{width:mainContentWidth + 'px','left':'80px'}">
      <el-col :span="1.5">
        <el-button icon="el-icon-arrow-left" size="middle" @click="handleReturn()">返回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-clickForbidden icon="el-icon-document-checked" size="middle" @click="handleSave">保存</el-button>
      </el-col>
    </el-row>
    <!-- form表单 -->
    <div ref="mainCont" class="main-content">
      <el-card ref="mainContent" class="box-card" shadow="never">
        <div slot="header" class="clearfix">
          <span>{{ title }}</span>
        </div>
        <div class="main-content-body">
          <el-form ref="formData" class="data-form" :rules="rules" :model="formData" label-width="100px">
            <div class="data-form-item">
              <div class="two-level-title">基本信息</div>
              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="proName">
                    <template slot="label">
                      <span class="labelTitle">项目名称</span>
                    </template>
                    <el-input v-model="formData.proName" clearable placeholder="请输入项目名称" />
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="proCode">
                    <template slot="label">
                      <span class="labelTitle">项目代码</span>
                    </template>
                    <el-input v-model="formData.proCode" clearable placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :lg="8" :xl="6">
                  <el-form-item label="建字第号" prop="buildManagementNum">
                    <el-input v-model="formData.buildManagementNum" clearable placeholder="请输入建字第号" size="medium">
                      <template slot="append">
                        <el-tooltip class="item" effect="dark" content="规划证上的建字第号" placement="top-start">
                          <i class="el-icon-question" />
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="grade">
                    <template slot="label">
                      <span class="labelTitle">项目等级</span>
                    </template>
                    <el-select v-model="formData.grade" style="width: 100%" clearable placeholder="请选择项目等级">
                      <el-option
                        v-for="item in proGrade"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="proTypeId">
                    <template slot="label">
                      <span class="labelTitle">项目类型</span>
                    </template>
                    <el-select v-model="formData.proTypeId" style="width: 100%" clearable placeholder="请选择项目类型">
                      <el-option
                        v-for="item in proTypeList"
                        :key="item.id"
                        :label="item.typeName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :xl="6" :lg="8">
                  <el-form-item label="合同金额" prop="contractAmountComdify">
                    <el-input v-model="formData.contractAmountComdify" clearable placeholder="请输入合同金额" @input="inputMoney">
                      <template slot="append"><el-button />万元</template>
                    </el-input>
                  </el-form-item>
                </el-col> -->
                <el-col :xl="6" :lg="8">
                  <el-form-item label="钻孔总数" prop="drillingCount">
                    <el-input v-model="formData.drillingCount" clearable placeholder="请输入钻孔总个数">
                      <template slot="append"><el-button />个</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="drillMember">
                    <template slot="label">
                      <span class="labelTitle">钻孔总延米</span>
                    </template>
                    <el-input v-model="formData.drillMember" clearable placeholder="请输入钻孔总延米">
                      <template slot="append"><el-button />m</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="province">
                    <template slot="label">
                      <span class="labelTitle">所在区域</span>
                    </template>
                    <el-cascader v-model="formData.currentProvince" placeholder="请选择所在区域" :props="cityNormalizer" :options="cityOptions" clearable style="width: 100%" @change="changeCitySelect">
                      <template slot-scope="{ data }">
                        <span>{{ data.label }}</span>
                      </template>
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="proNum">
                    <template slot="label">
                      <span class="labelTitle">项目编号</span>
                    </template>
                    <el-input v-model="formData.proNum" readonly placeholder="选择所在区域后回显" />
                  </el-form-item>
                </el-col>
                <selectCity :province="currentProvince" :address="formData.address" :x1="formData.x1" :y1="formData.y1" @getPosition="getPosition" />
                <el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="regionTypeName">
                    <template slot="label">
                      <span class="labelTitle">地貌类型</span>
                    </template>
                    <el-input v-model="formData.regionTypeName" readonly />
                  </el-form-item>
                </el-col>
                <!--<el-col :xl="6" :lg="8">
                  <el-form-item label="" prop="z">
                    <template slot="label">
                      <span class="labelTitle" v-html="`高&emsp;&emsp;程`" />
                    </template>
                    <el-input v-model="formData.z" clearable placeholder="请输入项目高程">
                      <template slot="append"><el-button />m</template>
                    </el-input>
                  </el-form-item>
                </el-col>-->
                <el-col :lg="8" :xl="6">
                  <el-form-item label="建筑规模" prop="scale">
                    <el-input v-model="formData.scale" clearable placeholder="请输入建筑规模" size="medium">
                      <template slot="append"><el-button />㎡</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :lg="8" :xl="6">
                  <el-form-item label="" prop="startTime">
                    <template slot="label">
                      <span class="labelTitle">计划日期</span>
                    </template>
                    <el-date-picker
                      v-model="planTime"
                      style="width: 100%"
                      size="medium"
                      type="daterange"
                      value-format="yyyy-MM-dd"
                      start-placeholder="计划开始日期"
                      end-placeholder="计划结束日期"
                      clearable
                      @change="planTimeChange"
                    />

                  </el-form-item>
                </el-col>
                <el-col :xl="24" :lg="24">
                  <el-form-item label="" prop="">
                    <template slot="label">
                      <span class="labelTitle" v-html="`备&emsp;&emsp;注`" />
                    </template>
                    <el-input v-model="formData.remark" clearable type="textarea" :rows="3" :maxlength="500" />
                  </el-form-item>
                </el-col>
                <el-col :xl="24" :lg="24">
                  <el-form-item label="" prop="landUsePermitList">
                    <template slot="label">
                      <span class="labelTitle" v-html="`规&ensp;划&ensp;证`" />
                    </template>
                    <img-uplode
                      ref="fileUplode"
                      :edit-file-list="landUsePermitList"
                      @getFileIdsList="getLandUsePermitPic"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!--建筑物-->
            <div class="data-form-item marginT10">
              <buildingInfo :table-data="BuildingList" @getTableFormData="getTableDuilding" />
            </div>
            <!-- 供应商单位 -->
            <div class="data-form-item">
              <div class="two-level-title">供应商</div>
              <companyDefinite v-for="(item, index) in organizationList" :key="index" :class="{marginT10: index !==0}" :company-title="item.typeName" :company-type="item.typeNum" :company-index="index" :table-data="organizationListData[item.typeNum]" @getTableFormData="getTableFormData" />
            </div>
          </el-form>
        </div>
      </el-card>
      <!-- 单位选择组件 -->
      <organization ref="selectClient" @organizationList="organizationList" />
    </div>
  </div>
</template>
<script>
/** 页面组件 start*/
// 建筑明细
import buildingInfo from './buildingInfo'
// 单位选择组件
import organization from '@/components/basicinfo/organization/index'
// 单位明细
import companyDefinite from './companyDefinite'
// 选择城市
import selectCity from '@/components/selectCity'
// 图片上传
import ImgUplode from '@/components/Upload/ImgUplode'
/** 页面组件 end*/

/** 页面接口 start*/
import { listByTreeProcessType, getRegionalType, getRegionalTypeById } from '@/api/common/area.js'
import { addProject, updateProject, getCode, getProjectById, enterpriseApi } from '@/api/projectManage/project/index'
import { getProTypeListNo } from '@/api/superviseBaseInfo/typeManage/projectType/index'
/** 页面接口 end*/

// 字段校验
import { integer, validateDouble, validateLongitude, validateLatitude, validateZ, divideMoney, delCommafyAmount, divideMoneyWan } from '@/utils/validate'
import { mapState } from 'vuex'
export default {
  components: {
    organization,
    companyDefinite,
    selectCity,
    buildingInfo,
    ImgUplode
  },
  data() {
    return {
      mainContentWidth: '',
      title: '', // 页面标题
      /** 表单 start*/
      formData: {
        proName: '', // 项目名称
        proCode: '', // 项目代码
        proNum: '', // 项目编号
        buildManagementNum: '', // 建字第号
        grade: '', // 项目等级
        proTypeId: '', // 项目类型
        contractAmountComdify: '', // 合同金额带逗号分割
        contractAmount: '', // 合同金额
        drillingCount: '', // 钻孔总个数
        drillMember: '', // 钻孔总延米
        currentProvince: '', // 所在区域
        nation: '', // 国家
        region: '', // 地区
        province: '', // 省
        city: '', // 市
        county: '', // 县
        address: '', // 项目地址
        x1: 0, // 坐标经度
        y1: 0, // 坐标纬度
        regionTypeId: '', // 地貌类型
        regionTypeName: '', // 地貌类型名称
        z: 0, // 高程
        scale: '', // 建筑规模
        startTime: '', // 计划开始时间
        endTime: '', //  计划结束时间
        remark: '', // 备注
        /* 附件 start */
        landUsePermitList: [], // 土地规划许可证附件
        /* 附件 end */
        buildList: '', // 建筑物
        proEnterpriseList: '' // 供应商单位列表
      },
      rules: { // 表单验证提示
        proName: [
          { required: true, message: '项目名称不得为空', pattern: '[^ \x22]+' }
        ],
        proCode: [
          { required: true, message: '项目代码不得为空', pattern: '[^ \x22]+' }
        ],
        proNum: [
          { required: true, message: '项目编号不得为空', pattern: '[^ \x22]+' },
          { required: true, max: 20, message: '项目编号长度不得超过 20 个字符' }
        ],
        buildManagementNum: [
          { required: true, message: '建字第号不得为空', pattern: '[^ \x22]+' }
        ],
        grade: [
          { required: true, message: '项目等级不得为空', pattern: '[^ \x22]+' }
        ],
        proTypeId: [
          { required: true, message: '项目类型不得为空', pattern: '[^ \x22]+' }
        ],
        contractAmountComdify: [
          { required: true, message: '合同金额不得为空' }
          // { validator: validAmountCheck, trigger: 'change' }
        ],
        drillingCount: [
          { required: true, message: '钻孔总数不得为空' },
          { validator: integer, trigger: 'blur' }
        ],
        drillMember: [
          { required: true, message: '钻孔总延米不得为空' },
          { validator: validateDouble, trigger: 'blur' }
        ],
        province: [
          { required: true, message: '所在区域不得为空' }
        ],
        address: [
          { required: true, message: '项目地址不得为空', pattern: '[^ \x22]+' }
        ],
        x: [
          { required: false, validator: validateLongitude, trigger: 'blur' }
        ],
        y: [
          { required: false, validator: validateLatitude, trigger: 'blur' }
        ],
        z: [
          { required: false, validator: validateZ, trigger: 'blur' }
        ],
        scale: [
          { required: false, validator: validateDouble, trigger: 'blur' }
        ],
        landUsePermitList: [
          { required: true, message: '请上传规划证', trigger: 'change' }
        ]
      },
      proTypeList: [], // 项目类型
      planTime: '', // 计划时间
      // 选择的城市
      currentProvince: '',
      cityOptions: [], // 城市数据
      cityNormalizer: {
        value: 'value',
        label: 'label',
        children: 'children'
      },
      /** 表单 end*/
      /* 附件 start*/
      landUsePermitList: [], // 土地规划许可证附件
      /* 附件 end*/
      /* 单位 start*/
      BuildingList: [], // 建筑列表
      organizationList: [], // 动态单位类型
      organizationListData: {} // 动态单位数据
      /* 单位 end*/
    }
  },
  computed: {
    ...mapState({
      proGrade: state => state.basicInfo.proGrade // 项目等级
    })
  },
  mounted() {
    /** 获取主题内容宽度 start*/
    setTimeout(() => {
      this.mainContentWidth = this.$refs.mainContent.$el.offsetWidth
    }, 100)
    const that = this
    window.onresize = () => {
      return (() => {
        that.mainContentWidth = that.$refs.mainContent.$el.offsetWidth
      })()
    }
    /** 获取主题内容宽度 end*/

    this.enterpriseApi()
    this.handleAdd()
    this.getRegionTree()
    this.getProTypeList()
  },
  methods: {
    // 计划日期变化
    planTimeChange(e) {
      this.formData.startTime = e[0]
      this.formData.endTime = e[1]
    },
    // 合同金额添加千位分割
    inputMoney(val) {
      const contractAmountComdify = divideMoney(val)
      this.$set(this.formData, 'contractAmountComdify', contractAmountComdify)
      this.formData.contractAmount = delCommafyAmount(this.formData.contractAmountComdify)
      this.$forceUpdate()
    },
    // 页面初始化
    handleAdd() {
      this.formData.id = this.$store.state.basicInfo.proId
      if (this.formData.id) {
        this.title = '项目信息编辑'
        this.handleUpdate(this.formData.id)
      } else {
        this.title = '项目信息新增'
      }
    },
    // 查询项目立项的详情
    async handleUpdate(id) {
      const { data } = await getProjectById(id)
      this.formData = { ...data }
      // 计划时间
      if (data.startTime && data.endTime) this.planTime = [data.startTime, data.endTime]
      // 建筑物明细
      this.BuildingList = data.buildList
      // 合同金额千位分割
      this.formData.contractAmountComdify = divideMoneyWan(this.formData.contractAmount)
      // 地区回显
      this.formData.currentProvince = [this.formData.nation, this.formData.region, this.formData.province, this.formData.city, this.formData.county] // 所在区域
      // this.getRegionalTypeById(this.formData.county) // 回显地貌
      this.currentProvince = this.formData.address
      // 附件回显
      this.landUsePermitList = data.landUsePermitList
      // 动态供应商单位转为json
      const endData = this.handlerEnterpriseDatas(this.formData.proEnterpriseList)
      if (endData.length > 0) {
        this.$nextTick(() => {
          endData.map(item => {
            this.organizationListData[item.sysEnterpriseType] = item.children
          })
        })
      }
    },
    // 保存
    handleSave() {
      this.$refs.formData.validate(async valid => {
        if (valid) {
          let proEnterpriseList = []
          // console.log(this.organizationListData)
          for (const i in this.organizationListData) {
            proEnterpriseList = [...proEnterpriseList, ...this.organizationListData[i]]
          }
          // const proEnterpriseList = this.flattenDeep(this.organizationListData)
          this.formData.proEnterpriseList = this.checkEditState(proEnterpriseList)
          // console.log(this.formData.proEnterpriseList)
          this.formData.buildList = this.checkEditState(this.formData.buildList)
          // this.formData.contractAmount = delcommafy(this.formData.contractAmountComdify)
          if (!this.checkEditState(this.formData.buildList) || !this.checkEditState(proEnterpriseList)) return
          if (this.formData.id) {
            const res = await updateProject(this.formData)
            this.msgInfoAdd(res, '/newProject/project')
          } else {
            const res = await addProject(this.formData)
            this.msgInfoAdd(res, '/newProject/project')
          }
        }
      })
    },
    // 动态供应商单位降维
    flattenDeep(arr1) {
      return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(this.flattenDeep(val)) : acc.concat(val), [])
    },
    // 处理返回的供应商
    handlerEnterpriseDatas(arr) {
      const tempArr = []
      const endData = []
      // const endJson = {}
      for (let i = 0; i < arr.length; i++) {
        if (tempArr.indexOf(arr[i].sysEnterpriseType) === -1) {
          endData.push({
            sysEnterpriseType: arr[i].sysEnterpriseType,
            children: [arr[i]]
          })
          tempArr.push(arr[i].sysEnterpriseType)
        } else {
          for (let j = 0; j < endData.length; j++) {
            console.log(endData[j].sysEnterpriseType === arr[i].sysEnterpriseType)
            if (endData[j].sysEnterpriseType === arr[i].sysEnterpriseType) {
              endData[j].children.push(arr[i])
              break
            }
          }
        }
      }
      // this.$nextTick(() => {
      //   endData.forEach((item) => { endJson[item.enterpriseType] = item.children })
      // })
      // console.log(endData)
      return endData
    },
    // 返回
    handleReturn() {
      this.$router.go(-1)
    },

    /** 单位信息 start*/
    // 建筑物
    getTableDuilding(tableFormData) {
      this.formData.buildList = tableFormData
    },
    // 判断单位否处在编辑状态
    checkEditState(tableFormData) {
      if (tableFormData && tableFormData.length > 0) {
        for (let i = 0; i < tableFormData.length; i++) {
          if (tableFormData[i].action === 'add' || tableFormData[i].action === 'edit') {
            this.msgInfo('请先保存正在编辑的数据')
            return false
          }
        }
        return tableFormData
      }
      return []
    },
    // 判断单位是否为空
    checkOrganization(tableFormData, name) {
      if (tableFormData.length <= 0) {
        this.msgInfo(`请添加` + name)
        return false
      }
      return true
    },
    // 获取动态单位单位
    getTableFormData(tableFormData, companyType) {
      this.organizationListData[companyType] = tableFormData
      // console.log(this.organizationListData)
    },
    // 获取动态供应商
    async enterpriseApi() {
      const { data: { rows }} = await enterpriseApi()
      this.organizationList = rows.filter(item => { return item.typeNum !== '04' })
      this.organizationList.map(item => {
        this.organizationListData[item.typeNum] = []
      })
    },
    /** 单位信息 end*/

    // 所属区域
    changeCitySelect(regionCode) {
      const [nation, region, province, city, county] = regionCode
      this.formData.nation = nation // 国家
      this.formData.region = region // 地区
      this.formData.province = province // 省
      this.formData.city = city// 市
      this.formData.county = county // 区/县
      this.getRegionCode(province, city, county)
      this.getRegionalType(county) // 根据选择的地区回显地貌
      if (regionCode.length) {
        this.getProCode(county) // 获取项目编码
      }
    },
    // 获取项目编码
    async getProCode(query) {
      const regionCode = { regionCode: query }
      const { data } = await getCode(regionCode)
      this.formData.proNum = data
    },
    // 根据选择的地区回显地貌
    async getRegionalType(county) {
      if (!county) return
      const { data: { value, lable }} = await getRegionalType(county)
      this.formData.regionTypeId = value // 地貌类型ID
      this.formData.regionTypeName = lable // 地貌类型名称
    },
    // 编辑时地区回显地貌
    async getRegionalTypeById(county) {
      if (!county) return
      const { data: { value, lable }} = await getRegionalTypeById(county)
      this.formData.regionTypeId = value // 地貌类型ID
      this.formData.regionTypeName = lable // 地貌类型名称
    },
    // 获取提交时地区编码
    getRegionCode() {
      const { formData: { province, city, county }} = this
      if (!county) return
      const region = this.cityOptions[0].children.find(item => {
        return item.children && item.children.some(city => city.value === province)
      })
      const sheng = region.children.find(sheng => sheng.value === province)
      const shi = sheng.children.find(shi => shi.value === city)
      const xian = shi.children.find(xian => xian.value === county)
      const currentProvince = (shi.label + xian.label) || ''
      // 清空后返回新的经纬度替换
      this.formData.x = 0
      this.formData.y = 0
      this.formData.address = ''
      this.currentProvince = currentProvince
    },
    // 获取区域树
    async getRegionTree() {
      const { data: { rows }} = await listByTreeProcessType({ regionCode: '' })
      this.cityOptions = this.deleteChildren(rows)
    },
    // 获取经纬度
    getPosition(data) {
      this.formData = { ...this.formData, ...data }
    },
    // 获取项目类型
    async getProTypeList() {
      const { data: { rows }} = await getProTypeListNo()
      this.proTypeList = rows
    },
    /** 附件上传 start */
    getLandUsePermitPic(fileIdsList, deleteFileIds, fileList) {
      this.formData.landUsePermitList = fileList
    }
    /** 附件上传 end */
  }

}

</script>

<style>
  .data-form .el-form-item{
    margin: 0;
  }
  .range-line {
    width: 12px;
    height: 1px;
    background: #ddd;
    float: left;
    margin: 17px 6px 0;
  }
  .range-input {
    float: left;
    width: 200px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
</style>
